var ListQuery = function (table, params) {
    var self = this;
    self.cols = params.cols;
    self.element = params.element;
    self.url = params.url;
    self.page = params.page;
    self.tableid = params.tableid;
    self.pageable = true;
    self.even = true;
    self.filter = params.filter;
    self.extraData = params.extraData;
    self.onRowChecked = params.onRowChecked;
    self.onReload = params.onReload;
    if (params.pageable) {
        self.pageable = params.pageable;
    }
    if (params.even == false) {
        self.even = params.even;
    }

    table.render({
        elem: self.element,
        url: self.url,
        id: self.tableid,
        method: 'post',
        cols: self.cols,
        size: 'sm',
        even: self.even,
        page: self.pageable,
        loading: true
    });

    if (self.filter) {
        /*table.on('checkbox(' + self.filter + ')', function (obj) {
            if (obj.type == 'one' && obj.checked) {
                self.onRowChecked(obj);
            }
        });*/
        table.on('tool(' + self.filter + ')', function (obj) {

            self.onRowChecked(obj);
        });
    }

    self.reload = function () {
        var whereData = self.extraData();
        table.reload(self.tableid, {
            page: {
                curr: self.page
            }
            , where: whereData
        });

        if (self.onReload) {
            self.onReload();
        }
    };

    self.getChecked = function () {
        var checkStatus = table.checkStatus(self.tableid);
        var data = checkStatus.data;
        return data;
    };
    self.getCheckedKeys = function () {
        var checkedData = self.getChecked();
        var data = new Array();
        for (var index in checkedData) {
            var itemData = checkedData[index];
            data.push(itemData.id);
        }
        return data;
    };
};

var TreeListQuery = function (table, params) {
    var self = this;
    self.cols = params.cols;
    self.element = params.element;
    self.url = params.url;
    self.page = params.page;
    self.tableid = params.tableid;
    self.pageable = true;
    self.single = false;
    self.filter = params.filter;
    self.extraData = params.extraData;
    self.onRowChecked = params.onRowChecked;
    self.datagrid = $(self.element);
    self.onReload = params.onReload;
    self.editIndex = null;
    if (params.pageable == false) {
        self.pageable = params.pageable;
    }
    if (params.single == true) {
        self.single = params.single;
    }
    $(self.element).treegrid({
        fitColumns: true,
        url: self.url,
        idField: "id",
        treeField: "name",
        animate: true,
        selectOnCheck: true,
        checkOnSelect: true,
        nowrap: false,
        striped: true,
        columns: self.cols,
        queryParam: self.extraData(),
        singleSelect: self.single,
        onSelect: function (rowIndex, rowData) {
            if (self.onRowChecked) {
                var row = new Object();
                row.data = rowData;
                self.onRowChecked(row);
            }
        },
        onLoadSuccess: function (data) {
            if (self.onReload) {
                self.onReload(data);
            }
        }
    });
    self.changeCols = function (cols) {
        self.cols = cols;
        $(self.element).treegrid({
            fitColumns: true,
            url: self.url,
            pagination: self.pageable,
            rownumbers: true,
            selectOnCheck: true,
            checkOnSelect: true,
            nowrap: false,
            striped: true,
            columns: self.cols,
            queryParam: self.extraData(),
            singleSelect: self.single,
            onSelect: function (rowIndex, rowData) {
                if (self.onRowChecked) {
                    var row = new Object();
                    row.data = rowData;
                    self.onRowChecked(row);
                }
            },
            onLoadSuccess: function (data) {
                if (self.onReload) {
                    self.onReload(data);
                }
            }
        });
    };
    self.reload = function (callback) {
        if (callback)
            self.onReload = callback;
        if (self.extraData) {
            self.datagrid.treegrid('load', self.extraData());
        }
        else {
            self.datagrid.treegrid('load');
        }
    };
    self.getChecked = function () {
        var data = $(self.element).treegrid('getSelections');
        return data;
    };
    self.getCheckedKeys = function () {
        var checkedData = self.getChecked();
        var data = new Array();
        for (var index in checkedData) {
            var itemData = checkedData[index];
            data.push(itemData.id);
        }
        return data;
    };
    self.getAllData = function () {
        return $(self.element).treegrid('getData');
    };
    self.selectRow = function (index) {
        $(self.element).treegrid('checkRow', index);
    };
    self.updateRow = function (index, data) {
        $(self.element).treegrid('updateRow', {index: index, row: data});
    };
    self.appendRow = function (data) {
        $(self.element).treegrid('appendRow', data);
    };
    self.insertRow = function (index, data) {
        $(self.element).treegrid('insertRow', {index: index, row: data});
    };
    self.deleteRow = function (index, data) {
        $(self.element).treegrid('deleteRow', index);
    };
    self.load = function (data) {
        return $(self.element).treegrid('loadData', data);
    };
};

var ListRelease = function (layer, query, params) {
    var self = this;
    self.url = params.url;
    self.msg = "确认删除记录吗？";
    if (params.msg) {
        self.msg = params.msg;
    }
    self.submit = function () {
        var data = query.getCheckedKeys();
        if (data.length < 1) {
            layer.msg("您没有选中记录");
            return;
        }
        layer.confirm(self.msg, {
            btn: ['确认', '取消'],
            yes: function (index) {
                try {
                    layer.load();
                    var keydata = {keys: data};
                    ajaxPost(self.url, keydata, function (data) {
                        layer.closeAll('loading');
                        layer.msg("操作成功");
                        layer.close(index);
                        query.reload();
                    }, function (error) {
                        layer.closeAll('loading');
                        layer.msg(error);
                    });
                }
                catch (e) {
                    layer.closeAll('loading');
                }
            }
        });
    }
}

var ListQuery2 = function (table, params) {

    var self = this;
    self.cols = params.cols;
    self.element = params.element;
    self.url = params.url;
    self.page = params.page;
    self.tableid = params.tableid;
    self.pageable = true;
    self.single = false;
    self.filter = params.filter;
    self.extraData = params.extraData;
    self.onRowChecked = params.onRowChecked;
    self.datagrid = $(self.element);
    self.onReload = params.onReload;
    self.editIndex = null;
    if (params.pageable == false) {
        self.pageable = params.pageable;
    }
    if (params.single == true) {
        self.single = params.single;
    }
    $(self.element).datagrid({
        fitColumns: true,
        url: self.url,
        pagination: self.pageable,
        rownumbers: true,
        selectOnCheck: true,
        checkOnSelect: true,
        nowrap: false,
        striped: true,
        columns: self.cols,
        queryParam: self.extraData(),
        singleSelect: self.single,
        onSelect: function (rowIndex, rowData) {
            if (self.onRowChecked) {
                var row = new Object();
                row.data = rowData;
                self.onRowChecked(row);
            }
        },
        onLoadSuccess: function (data) {
            if (self.onReload) {
                self.onReload(data);
            }
        }
    });
    self.reload = function (callback) {
        self.onReload = callback;
        if (self.extraData) {
            self.datagrid.datagrid('load', self.extraData());
        }
        else {
            self.datagrid.datagrid('load');
        }
    };
    self.getChecked = function () {
        var data = $(self.element).datagrid('getSelections');
        return data;
    };
    self.getCheckedKeys = function () {
        var checkedData = self.getChecked();
        var data = new Array();
        for (var index in checkedData) {
            var itemData = checkedData[index];
            data.push(itemData.id);
        }
        return data;
    };
    self.getAllData = function () {
        return $(self.element).datagrid('getData');
    };
    self.selectRow = function (index) {
        $(self.element).datagrid('checkRow', index);
    };
    self.updateRow = function (index, data) {
        $(self.element).datagrid('updateRow', {index: index, row: data});
    };
    self.appendRow = function (data) {
        $(self.element).datagrid('appendRow', data);
    };
    self.insertRow = function (index, data) {
        $(self.element).datagrid('insertRow', {index: index, row: data});
    };
    self.deleteRow = function (index, data) {
        $(self.element).datagrid('deleteRow', index);
    };
    self.load = function (data) {
        return $(self.element).datagrid('loadData', data);
    };
}


var ListAdd = function (layer, params, query) {
    var self = this;
    self.title = params.title;
    self.url = params.url;
    self.width = params.width;
    self.height = params.height;
    self.getUrl = params.getUrl;
    self.isfull = params.isfull ? true : false;
    self.layerIndex = null;
    self.openDialog = function () {
        var tempUrl = self.url;
        if (self.getUrl) {
            tempUrl = self.getUrl(self.url);
        }
        self.layerIndex = layer.open({
            type: 2,
            title: self.title,
            shadeClose: true,
            skin: 'layui-layer-lan',
            shade: 0.8,
            offset: '20px',
            area: [self.width, self.height],
            content: tempUrl
        });
        if (self.isfull == true) {
            layer.full(self.layerIndex);
        }
    };
    self.closeDialog = function () {
        layer.close(self.layerIndex);
    };
    self.addCompleted = function () {
        self.closeDialog();
        query.reload();
    }
};


var ListExport2 = function (layer, query, params) {
    var self = this;
    self.url = params.url;
    self.submit = function () {
        var items = query.getCheckedKeys();
        if (items.length < 1) {
            layer.msg("还没有选中记录！");
            return;
        }
        else if (items.length > 1) {
            layer.msg("只能选择一条记录！");
            return;
        }
        var id = items[0];
        layer.confirm('确认导出该问卷吗？', {
            btn: ['确认', '取消'],
            yes: function (index) {
                try {
                    layer.closeAll();
                    var requestUrl = self.url + "?id="+id;
                    form = $("<form method='post'></form>"),
                        form.attr({"action":requestUrl});
                    form.appendTo(document.body);
                    form.submit();
                }
                catch (e) {
                    layer.closeAll('loading');
                }
            }

        });
    }
}

var ListEdit = function (layer, params, query) {
    var self = this;
    self.title = params.title;
    self.url = params.url;
    self.width = params.width;
    self.height = params.height;
    self.isfull = params.isfull ? true : false;
    self.layerIndex = null;
    self.openDialog = function () {
        var items = query.getCheckedKeys();
        if (items.length < 1) {
            layer.msg("还没有选中记录！");
            return;
        }
        else if (items.length > 1) {
            layer.msg("只能选择一条记录！");
            return;
        }

        var id = items[0];
        self.layerIndex = layer.open({
            type: 2,
            title: self.title,
            shadeClose: true,
            skin: 'layui-layer-lan',
            offset: '20px',
            shade: 0.8,
            area: [self.width, self.height],
            content: self.url + "/" + id,
            maxmin: self.isfull
        });
        if (self.isfull == true) {
            layer.full(self.layerIndex);
        }
    }
    self.closeDialog = function () {
        layer.close(self.layerIndex);
    };
    self.editCompleted = function () {
        self.closeDialog();
        query.reload();
    }
};

var updatePassword = function (layer, params) {
    var self = this;
    self.title = params.title;
    self.url = params.url;
    self.width = params.width;
    self.height = params.height;
    self.isfull = params.isfull ? true : false;
    self.layerIndex = null;
    self.openDialog = function () {
        self.layerIndex = layer.open({
            type: 2,
            title: self.title,
            shadeClose: true,
            skin: 'layui-layer-lan',
            offset: '20px',
            shade: 0.8,
            area: [self.width, self.height],
            content: self.url,
            maxmin: self.isfull
        });
        if (self.isfull == true) {
            layer.full(self.layerIndex);
        }
    }
    self.closeDialog = function () {
        layer.close(self.layerIndex);
    };
    self.editCompleted = function () {
        self.closeDialog();
    }
};

var ListDelete = function (layer, query, params) {
    var self = this;
    self.url = params.url;
    self.submit = function () {
        var data = query.getCheckedKeys();
        if (data.length < 1) {
            layer.msg("您没有选中记录");
            return;
        }
        layer.confirm('确认删除记录吗？', {
            btn: ['确认', '取消'],
            yes: function (index) {
                try {
                    layer.load();
                    var keydata = {keys: data};
                    ajaxPost(self.url, keydata, function (data) {
                        layer.closeAll('loading');
                        layer.msg("操作成功");
                        layer.close(index);
                        query.reload();
                    }, function (error) {
                        layer.closeAll('loading');
                        layer.msg("操作失败");
                    });
                }
                catch (e) {
                    layer.closeAll('loading');
                }
            }

        });
    }
}

var FormAdd = function (form, layer, add, params, formId, validFields) {
    var self = this;
    self.url = params.url;
    self.getData = params.getData;
    self.valid = new FormValidation(formId, validFields);
    self.valid.initValid();
    self.close = function () {
        add.closeDialog();
    };
    self.submit = function () {
        try {
            if (self.valid.isValid()) {
                layer.load();
                var data = self.getData();
                ajaxPost(self.url, data, function (data) {
                    layer.closeAll('loading');
                    parent.layer.msg("操作成功");
                    add.addCompleted();
                }, function (error) {
                    layer.closeAll('loading');
                    parent.layer.msg("操作失败");
                });
            }
        }
        catch (e) {
            layer.closeAll('loading');
        }
    }
}

var FormEdit = function (form, layer, edit, params, formId, validFields) {
    var self = this;
    self.url = params.url;
    self.getData = params.getData;
    self.valid = new FormValidation(formId, validFields);
    self.valid.initValid();
    self.close = function () {
        edit.closeDialog();
    };
    self.submit = function () {
        try {
            if (self.valid.isValid()) {
                layer.load();
                var data = self.getData();
                ajaxPost(self.url, data, function (data) {
                    layer.closeAll('loading');
                    parent.layer.msg("操作成功");
                    edit.editCompleted();
                }, function (error) {
                    console.log(error);
                    layer.closeAll('loading');
                    parent.layer.msg("操作失败");
                });
            }
        }
        catch (e) {
            layer.closeAll('loading');
        }
    }
}

var FormEdit2 = function (form, layer, edit, params, formId, validFields) {
    var self = this;
    self.url = params.url;
    self.getData = params.getData;
    self.valid = new FormValidation(formId, validFields);
    self.valid.initValid();
    self.close = function () {
        edit.closeDialog();
    };
    self.submit = function () {
        try {
            if (self.valid.isValid()) {
                layer.load();
                var data = self.getData();
                ajaxPost(self.url, data, function (data) {
                    layer.closeAll('loading');
                    parent.layer.msg("操作成功");
                    edit.editCompleted();
                }, function (error) {
                    console.log(error);
                    layer.closeAll('loading');
                    parent.layer.msg(error);
                });
            }
        }
        catch (e) {
            layer.closeAll('loading');
        }
    }
}

var FormValidation = function (formId, validFields) {
    var self = this;
    self.formId = formId;
    self.initValid = function () {
        $("#" + formId).bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: validFields
        });
    };
    self.isValid = function () {
        $("#" + formId).bootstrapValidator('validate');
        return $("#" + formId).data("bootstrapValidator").isValid();
    }
}


$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


var ajaxPost = function (url, data, successMethod, errorMethod, timeout, synch, type) {
    var applyType = "post";
    var applySynch = true;
    var applyTimeout = 30000;
    if (type) {
        applyType = type;
    }
    if (synch) {
        applySynch = synch;
    }
    if (timeout) {
        applyTimeout = timeout;
    }
    var ap = $.ajax({
        url: url,
        type: applyType,
        timeout: applyTimeout,
        data: data,
        synch: applySynch,
        success: function (data) {
            if (data.success == true) {
                if (successMethod) {
                    successMethod(data.data);
                }
            }
            else {
                if (errorMethod) {
                    errorMethod(data.message);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (errorMethod) {
                errorMethod("服务器错误!", XMLHttpRequest, textStatus);
            }
        }
    });

    return ap;
};

String.format = function () {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};

Date.prototype.format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var contextRoot = $("meta[name='context-path']").attr("content");

var ListExport = function (layer, params) {
    var self = this;
    self.url = params.url;
    self.confirmText = params.confirmText;
    self.extraData = params.extraData;
    self.export = function () {
        if (!self.confirmText) {
            self.confirmText = "确认导出记录吗？";
        }
        self.confirmText += "(最大1000条)";
        layer.confirm(self.confirmText, {
            btn: ['确认', '取消'],
            yes: function (index) {
                try {
                    layer.close(index);
                    var data = self.extraData();
                    var requestUrl = self.url + "?";
                    var requestParam = "";
                    var data = self.extraData();
                    console.log(requestUrl + requestParam);
                    var body = $(document.body),
                        form = $("<form method='post'></form>"),
                        input;
                    form.attr({"action":requestUrl + requestParam});
                    $.each(data,function(key,value){
                        input = $("<input type='hidden'>");
                        input.attr({"name":key});
                        input.val(value);
                        form.append(input);
                    });
                    form.appendTo(document.body);
                    form.submit();
                    document.body.removeChild(form[0]);
                }
                catch (e) {
                }
            }
        });
    }
}